package com.shen.accountbook.module.home.detailedfragment;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.bumptech.glide.Glide;
import com.shen.accountbook.R;
import com.shen.accountbook.bean.NoteBeanByDay;
import com.shen.accountbook.bean.temp.NoteBeanTemp;
import com.shen.accountbook.module.base.MVPFragment;
import com.shen.accountbook.module.home.booknote.BookNoteActivity;
import com.shen.accountbook.stickyheader.StickyHeaderGridLayoutManager;
import com.shen.accountbook.utils.DateUtils;
import com.shen.accountbook.utils.FormatUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.shen.accountbook.config.Constant.colorRes;
import static com.shen.accountbook.config.Constant.distance;

/**
 * author:  shen
 * date:    2018/8/27
 *
 * 明细标签
 */
public class DetailFragment extends MVPFragment<DetailPresenterImpl> implements DetailView {


    @BindView(R.id.layout_data_top)
    LinearLayout mLayoutDataTop;

    /** 年份 */
    @BindView(R.id.tv_year_top)
    TextView mTvYearTop;
    /** 月份 */
    @BindView(R.id.tv_month_top)
    TextView mTvMonthTop;

    /** 结余(元) */
    @BindView(R.id.tv_cash_surplus_top)
    TextView mTvCashSurplusTop;
    /** 相比上月收入 */
    @BindView(R.id.tv_cash_compared_top)
    TextView mTvCashComparedTop;


    @BindView(R.id.rv_list_detailfragment)
    RecyclerView mRvList;
    @BindView(R.id.swipe_detailfragment)
    SwipeRefreshLayout mSwipe;

    @BindView(R.id.fbtn_detailfragment)
    FloatingActionButton mFBtn;

    private static final int SPAN_SIZE = 1;
    private StickyHeaderGridLayoutManager mLayoutManager;
    private DetailAdapter mAdapter;
    List<NoteBeanByDay> mNoteBeanByDayList = new ArrayList<>();

    @Override
    protected DetailPresenterImpl createPresent(Context context) {
        return new DetailPresenterImpl(context, this);
    }

    @Override
    public int getResId() {
        return R.layout.fragment_detail;
    }

    @Override
    protected void initData() {
        setTopView();
        setSwipe();
        setRvList();
    }

    @Override
    protected void initEvent() {
        getData();
    }


    private void setTopView(){
        initTime();
    }

    private void setSwipe(){

        mSwipe.setColorSchemeColors(colorRes, colorRes);            // 改变加载显示的颜色
        mSwipe.setDistanceToTriggerSync(distance);                  // 设置向下拉多少出现刷新
        mSwipe.setProgressViewEndTarget(false, distance);     // 设置刷新出现的位置
        mSwipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mSwipe.setRefreshing(false);
                getData();
            }
        });
    }

    private void setRvList(){
        mLayoutManager = new StickyHeaderGridLayoutManager(SPAN_SIZE);
        // 设置与第一节项目重叠的页眉底部边距大小。用于创建页眉底边阴影。
        mLayoutManager.setHeaderBottomOverlapMargin(5);

        mRvList.setItemAnimator(new DefaultItemAnimator() {
            @Override
            public boolean animateRemove(RecyclerView.ViewHolder holder) {
                dispatchRemoveFinished(holder);
                return false;
            }
        });
        mRvList.setLayoutManager(mLayoutManager);
        mAdapter = new DetailAdapter(mContext, mNoteBeanByDayList);
        mRvList.setAdapter(mAdapter);


        mRvList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                switch (newState){
                    case 0:
                        Glide.with(DetailFragment.this).resumeRequests();
                        break;

                    case 1:
                    case 2:
                        Glide.with(DetailFragment.this).pauseRequests();
                        break;
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }

    private void getData() {
        mPresenter.getBeanByDate(mTvYearTop.getText().toString() + mTvMonthTop.getText().toString() + "月");
    }


    @OnClick({R.id.fbtn_detailfragment, R.id.layout_data_top})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.fbtn_detailfragment:                              /* 加一笔 */
                startActivity(null, BookNoteActivity.class);
                break;

            case R.id.layout_data_top:                                  /* 选择时间 */
                selectTime();
                break;
        }
    }



    /**
     * 选择日期
     */
    private void selectTime() {
        TimePickerView startTimePicker = new TimePickerView.Builder(mContext, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                SimpleDateFormat sdfY = new SimpleDateFormat("yyyy年");
                SimpleDateFormat sdfM = new SimpleDateFormat("MM");
                mTvYearTop.setText(sdfY.format(date));
                mTvMonthTop.setText(sdfM.format(date));
                getData();
            }
        }).setRange(2018,2050)
                .setType(new boolean[]{true,true,false,false,false,false})
                .build();
        startTimePicker.show();
    }


    private void initTime(){
        SimpleDateFormat sdfY = new SimpleDateFormat("yyyy年");
        SimpleDateFormat sdfM = new SimpleDateFormat("MM");
        mTvYearTop.setText(sdfY.format(new Date()));
        mTvMonthTop.setText(sdfM.format(new Date()));
    }

    @Override
    public void setData(List<NoteBeanTemp> noteBeanTemps) {
        if(mNoteBeanByDayList.size() > 0){
            mNoteBeanByDayList.clear();
        }

        double moneyByDay = 0;
        double moneyByMonth = 0;
        NoteBeanTemp beanOld = null;
        for(NoteBeanTemp bean : noteBeanTemps){
            if(beanOld == null){
                moneyByDay = bean.getMoney();
                addFirstNoteBean(bean);
            }else {
                if(bean.getCreateDate().equals(beanOld.getCreateDate())){
                    moneyByDay += bean.getMoney();
                    mNoteBeanByDayList.get(mNoteBeanByDayList.size() - 1).getNoteList().add(bean);
                    mNoteBeanByDayList.get(mNoteBeanByDayList.size() - 1).setMoney(setMoney(moneyByDay));
                }else {
                    moneyByDay = bean.getMoney();
                    addFirstNoteBean(bean);
                }
            }
            moneyByMonth += bean.getMoney();
            beanOld = bean;
        }


        mTvCashSurplusTop.setText(FormatUtils.double2DecimalFormat(moneyByMonth, 2));
        mAdapter.setDatas(mNoteBeanByDayList);
        mAdapter.notifyAllSectionsDataSetChanged();  //需调用此方法刷新
    }

    /**
     * 设置每天的第一个
     * @param bean
     * @return
     */
    private void addFirstNoteBean(NoteBeanTemp bean) {
        NoteBeanByDay noteBeanByDay = new NoteBeanByDay();
        noteBeanByDay.setTime(bean.getCreateDate() + " " +
                DateUtils.getWeekByStrDate(bean.getCreateDate(), DateUtils.FORMAT2));
        noteBeanByDay.setMoney(setMoney(bean.getMoney()));

        List<NoteBeanTemp> beanTempList = new ArrayList<>();
        beanTempList.add(bean);
        noteBeanByDay.setNoteList(beanTempList);

        mNoteBeanByDayList.add(noteBeanByDay);
    }

    @NonNull
    private String setMoney(double money) {
        return "支出：" + FormatUtils.double2DecimalFormat(money, 2);
    }
}

